package com.har.modules.business.controller;

import com.har.common.config.UploadConfig;
import com.har.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author macwy
 * @Title:har-finance
 * @Package com.har.modules.business.controller
 * @Description 文件上传
 * @date 2018/6/27 11:21
 * @Version 1.0
 */
@RestController
public class UploadController {

    @Autowired
    private UploadConfig uploadConfig;

    @RequestMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws IOException {
        //如果文件不为空，写入上传路径
        if (!file.isEmpty()) {
            //上传文件名
            String filename = file.getOriginalFilename();
            File filepath = new File(uploadConfig.getSavePath(), filename);
            //判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            String fileName = System.currentTimeMillis()+filename.substring(filename.indexOf("."));
            String savePath = uploadConfig.getSavePath()+File.separator+fileName;
            String accessPath = uploadConfig.getAccessPath() + File.separator + fileName;
            file.getInputStream();

            //将上传文件保存到一个目标文件当中
            file.transferTo(new File(savePath));
           return R.ok().put("savePath",accessPath).put("url",accessPath);
        }
        return R.error();
    }

}
